package codeRandomThoughts.Test203移除链表元素;

import codeRandomThoughts.utils.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class Solution {
    //public ListNode removeElements(ListNode head, int val) {
    //    //头节点因为没有前驱结点是它变成了特殊情况
    //    //可以考虑消除掉特殊情况,即将头节点变成第二个结点
    //    ListNode fakeHead = new ListNode();
    //    fakeHead.next = head;
    //    ListNode pointer = fakeHead;
    //    while (pointer.next!=null){
    //        if (pointer.next.val==val){
    //            pointer.next = pointer.next.next;
    //        }else {
    //            pointer = pointer.next;
    //        }
    //    }
    //    return fakeHead.next;
    //}

    public ListNode removeElements(ListNode head, int val) {
        ListNode header = new ListNode();
        header.next = head;
        ListNode pointer = header;
        while (pointer.next != null) {
            if (pointer.next.val == val) {
                pointer.next = pointer.next.next;
            } else {
                pointer = pointer.next;
            }
        }
        return header.next;
    }
}

